package org.subatu.orm.query;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.subatu.orm.core.BaseMapper;
import org.subatu.orm.query.base.SqlData;
import org.subatu.orm.query.base.SqlStruct;
import org.subatu.orm.query.condition.Sql;

import java.util.List;
import java.util.Map;

public class SqlWrapper<E> implements Sql {
    private static Logger logger = LoggerFactory.getLogger(SqlWrapper.class);

    private BaseMapper baseMapper;

    public SqlWrapper(BaseMapper baseMapper) {
        this.baseMapper = baseMapper;
    }

    // sql中的各种数据
    private SqlData sqlData = new SqlData();

    @Override
    public SqlData sqlData() {
        return sqlData;
    }

    @Override
    public List<Map<String, Object>> list() {
        return this.list(null);
    }

    @Override
    public <T> List<T> list(Class<T> resultType) {
        SqlStruct sqlStruct = this.buildSql();
        logger.info("\nsql------>{}\nparams--->{}", sqlStruct.getSql(), sqlStruct.getParams());
        List list = baseMapper.selectList(sqlStruct.getSql(), sqlStruct.getParams(), resultType);
        return list;
    }

    public Map<String, Object> one() {
        return one(true);
    }

    public Map<String, Object> one(boolean strict) {
        List<Map<String, Object>> list = this.list();
        Assert.isTrue(strict && list.size() < 2, "one()查询数量大于1,请核对");
        if (list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    @Override
    public <T> T one(Class<T> clazz) {
        return one(clazz, true);
    }

    @Override
    public <T> T one(Class<T> clazz, boolean strict) {
        List<T> list = this.list(clazz);
        Assert.isTrue(strict && list.size() < 2, "one()查询数量大于1,请核对");
        if (list.size() == 0) {
            return null;
        }
        return list.get(0);
    }


}
